package com.block.source.service.receive;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.enums.InfoTypeEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.db.entity.*;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.api.PaiYiDaiParam;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.ISourceReceiveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class PaiYiDaiReceiveService extends ISourceReceiveService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

//        String data = JSONObject.parseObject(paramContent).getString("data");
        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息为空"));
            return sourceApiResult;
        }
        String data = jsonObjectParamContent.getString("data");
        String paramContentData = SecureUtil.aes(sourceBaseInfo.getApiSecret().getBytes()).decryptStr(data);
        UserDataParam userDataParam = this.getUserDataParam(paramContentData);


        // 通过城市编码,获取城市信息
        AddressInfo addressInfo = addressInfoService.getAddressInfoByCityCode(userDataParam.getCityCode());
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getError("城市信息为空"));
            return sourceApiResult;
        }

        // 设置省市信息
        userDataParam.setCityCode(addressInfo.getCityCode());
        userDataParam.setCity(addressInfo.getCity());
        userDataParam.setProvinceCode(addressInfo.getProvinceCode());
        userDataParam.setProvince(addressInfo.getProvince());



        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("进件传入的信息为空"));
            return sourceApiResult;
        }
        String data = jsonObjectParamContent.getString("data");
        String paramContentData = SecureUtil.aes(sourceBaseInfo.getApiSecret().getBytes()).decryptStr(data);

        PaiYiDaiParam paiYiDaiParam = JSON.parseObject(paramContentData, PaiYiDaiParam.class);

        UserDataParam userDataParam = this.getUserDataParam(paramContentData);

        userDataParam.setMobile(paiYiDaiParam.getPhone());
        userDataParam.setRealName(paiYiDaiParam.getUserName());

        String productId = paiYiDaiParam.getProductId();
        SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectByChannelCodeAndOutOrderNo(sourceBaseInfo.getChannelCode(), productId);
        userDataParam.setOrderNo(String.valueOf(pushResultInfo.getId()));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {


        SourceApiResult sourceApiResult = new SourceApiResult();

        MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
        SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();
        MerchantThirdBaseInfo thirdBaseInfo = sourceApiParam.getThirdBaseInfo();
        List<MerchantThirdProtocolInfo> thirdProtocolInfoList = sourceApiParam.getThirdProtocolInfoList();

        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 0);
        returnObject.put("message", "匹配成功！");
        JSONObject dataObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        if (StrUtil.equals(merchantBaseInfo.getInfoType(), InfoTypeEnum.APIS.getValue())){
            // 下游是 非 apis 类型
            dataObject.put("companyName", thirdBaseInfo.getCompanyName());
            String companyLogo = thirdBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", companyLogo);
            }
            dataObject.put("productName", thirdBaseInfo.getProductName());
            dataObject.put("productId", pushResultInfo.getOutOrderNo());
            //协议地址
            for (MerchantThirdProtocolInfo protocolInfo : thirdProtocolInfoList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("agreementName",protocolInfo.getProtocolName());
                jsonObject.put("agreementUrl", protocolInfo.getProtocolUrl());
                jsonArray.add(jsonObject);
            }
        }else {
            dataObject.put("companyName", merchantBaseInfo.getCompanyName());
            String companyLogo = merchantBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", merchantBaseInfo.getCompanyLogo());
            }
            dataObject.put("productName", merchantBaseInfo.getInfoName());
            dataObject.put("productId", pushResultInfo.getOutOrderNo());
            //协议地址
            JSONObject jsonObject = new JSONObject();
            ChannelBaseInfo baseInfoByCode = channelCommonService.getBaseInfoByCode(sourceBaseInfo.getChannelCode());
            ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(baseInfoByCode.getAppCode());
            String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), pushResultInfo.getOrderNo(), pushResultInfo.getOrderItemNo());
            jsonObject.put("agreementName","授权协议");
            jsonObject.put("agreementUrl", protocolUrl);
            jsonArray.add(jsonObject);
        }

        dataObject.put("agreement", jsonArray);
        returnObject.put("data", dataObject);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO,SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();

        JSONObject returnObject = new JSONObject();

        JSONObject data = resultInfoVO.getData();
        String respCode = resultInfoVO.getRespCode();

        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()){
            String status = data.getString("status");
            if (StrUtil.equals(status, "000")){
                returnObject = this.getSuccess();
                returnObject.put("data",new JSONObject());
                sourceApiResult.setReturnObject(returnObject);
                return sourceApiResult;
            }
        }

        returnObject = this.getError("推送失败");
        returnObject.put("data",new JSONObject());
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 500);
        returnObject.put("message", message);
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 0);
        returnObject.put("message", "推送成功");
        return returnObject;
    }

    @Override
    public UserDataParam getUserDataParam(String paramContent) {

        PaiYiDaiParam paiYiDaiParam = JSON.parseObject(paramContent, PaiYiDaiParam.class);

        UserDataParam userDataParam = new UserDataParam();

        Integer randomInt = RandomUtil.randomInt(Integer.MAX_VALUE);
        userDataParam.setOutOrderNo(String.valueOf(randomInt));

        userDataParam.setMobileMd5(paiYiDaiParam.getPhoneMd5());
        userDataParam.setMobile(paiYiDaiParam.getPhone());
        userDataParam.setRealName(paiYiDaiParam.getUserName());

        String sex = paiYiDaiParam.getSex()==1?"1":"2";
        userDataParam.setSex(sex);


        userDataParam.setAge(Integer.valueOf(paiYiDaiParam.getAge()));
        userDataParam.setCity(paiYiDaiParam.getCity());
        userDataParam.setCityCode(paiYiDaiParam.getCityCode());

        userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt007.getValue());
        userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl001.getValue());
        userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr001.getValue());
        userDataParam.setWeili(BaseTypeInfoEnum.WeiLi.wl001.getValue());
        userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt001.getValue());
        userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());
        userDataParam.setUserIp("127.0.0.1");

        Integer demandAmount = paiYiDaiParam.getLoanAmount();
        if (demandAmount < 30000) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
        } else if (demandAmount < 50000) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la002.getValue());
        } else if (demandAmount < 100000) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la003.getValue());
        } else if (demandAmount < 200000) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la004.getValue());
        } else {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la005.getValue());
        }

        Integer houseId = paiYiDaiParam.getHouseProperty();
        if (ObjectUtil.equals(houseId, Integer.valueOf(2))){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu003.getValue());
        }else{
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu001.getValue());
        }

        Integer insureId = paiYiDaiParam.getBdStatus();
        if (ObjectUtil.equals(insureId, Integer.valueOf(2))){
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx003.getValue());
        }else{
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx001.getValue());
        }

        Integer overdueId = paiYiDaiParam.getOverdue();
        if (ObjectUtil.equals(overdueId, Integer.valueOf(3))){
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq001.getValue());
        }else {
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq002.getValue());
        }

        Integer providentId = paiYiDaiParam.getFund();
        if (ObjectUtil.equals(providentId, Integer.valueOf(2))){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj003.getValue());
        }else{
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj001.getValue());
        }

        Integer sesameId = paiYiDaiParam.getZhimaCredit();
        if (ObjectUtil.equals(sesameId, Integer.valueOf(5))){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm005.getValue());
        }else if (ObjectUtil.equals(sesameId, Integer.valueOf(4))){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm004.getValue());
        }else if (ObjectUtil.equals(sesameId, Integer.valueOf(3))){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm003.getValue());
        }else{
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm002.getValue());
        }

        Integer socialId = paiYiDaiParam.getHas();
        if (ObjectUtil.equals(socialId, Integer.valueOf(2))){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb003.getValue());
        }else{
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb001.getValue());
        }

        Integer vehicleId = paiYiDaiParam.getCarProperty();
        if (ObjectUtil.equals(vehicleId, Integer.valueOf(2))){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car002.getValue());
        }else{
            userDataParam.setCar(BaseTypeInfoEnum.Car.car001.getValue());
        }

        Integer vocationId = paiYiDaiParam.getJob();
        if (ObjectUtil.equals(vocationId, Integer.valueOf(0))){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
        }else if (ObjectUtil.equals(vocationId, Integer.valueOf(1))){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz002.getValue());
        }else if (ObjectUtil.equals(vocationId, Integer.valueOf(3))){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz003.getValue());
        }if (ObjectUtil.equals(vocationId, Integer.valueOf(4))){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz004.getValue());
        }else{
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz005.getValue());
        }

        userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt003.getValue());

        return userDataParam;
    }

}
